var Messages = {

    selected_row_id : null,

    /* dataTable Object */
    objGrid: null,

    /* Function init
     * @param void
     * @return void
     * @access public
     * */
    init:function(){
        var self = this;

        //Init message click
        self.initloadMessage();
        //Init Delete message
        self.initDeleteMessage();

        $('#user-save-btn').click(function(){
            self.saveUser();
        });

        $('#user-cancel-btn').click(function(){
            document.getElementById('user-form').reset();
            $.validationEngine.closePrompt('.formError',true);
            $.colorbox.close();
            self.selected_row_id = null;
        });

        jLib.afterClosePopUpForm('user-form',function(){
            self.selected_row_id = null;
            document.getElementById('user-form').reset();
        });

        $('#new_msg').click(function(){
            self.newMsg();
        });
        $('#send-btn').click(function(){
            self.saveMessage();
        });

        $("#form-new-msg").validationEngine();
    },

    initloadMessage: function(){
        $('ul.message-menu > li > a.read').click(function(){
            //Do some cool animation here
            var msg_id = $(this).attr('data-id');
            var msg_type = $(this).attr('msg-type');
            var msg_status = $(this).attr('msg-status');
            var url = $('#messages-url').val();
            var query = 'action=load&data-id='+msg_id+'&msg-type='+msg_type+'&msg-status='+msg_status;
            $.ajax({
                url:url,
                data:query,
                dataType:'json',
                type:'POST',
                success:function (response) {
                    var msg = response.data;
                    console.log(msg);
                    $('.msg-window .msg-subject').html(msg['Message']['title']);
                    $('.msg-window .msg-from').html('From: '+msg['User']['first_name']+' '+msg['User']['last_name']);
                    var recivers = '';
                    for(var x in msg['MessageReciever']){
                        recivers += msg['MessageReciever'][x]['User']['first_name']+' '+msg['MessageReciever'][x]['User']['last_name']+', '
                    }
                    $('.msg-window .msg-content').html(msg['Message']['content']);
                    $('.msg-window .msg-to').html('To: '+recivers);
                    $('.msg-window').show();

                },
                error:function (xhr) {
                    console.log(xhr.responseText);
                    jLib.serverError();
                }
            });
        });
    },


    initDeleteMessage: function(){
        $('ul.message-menu > li > span >a.delete').click(function(){

            //Do some cool animation here
            var parent_li = $(this).parent().parent();

            var msg_id = $(this).attr('data-id');
            var delete_type = $(this).attr('delete-type');
            var delete_action = $(this).attr('delete-action');

            var url = $('#messages-url').val();
            var query = 'action=delete&data-id='+msg_id+'&delete-type='+delete_type+'&delete-action='+delete_action;
            $.modal.confirm('Are you sure you want to continue ?', function () {
                $.ajax({
                    url:url,
                    data:query,
                    dataType:'json',
                    type:'POST',
                    success:function (response) {
                        var txt = '';
                        if (typeof response.mesg == 'object') {
                            for (megTxt in response.mesg) {
                                txt += response.mesg[megTxt] + '<br />';
                            }
                        }
                        else {
                            txt = response.mesg
                        }
                        if (response.code === 0) {
                            jLib.message(txt, 'success',function(modal){
                                modal.closeModal();
                                parent_li.remove();
                                window.location = url;
                            });
                        }
                        //* When there are Errors *//*
                        else if (response.code === 1) {
                            jLib.serverError(txt);
                        }
                    },
                    error:function (xhr) {
                        console.log(xhr.responseText);
                        jLib.serverError();
                    }
                });

            }, function () {
                return false;
            })


        });
    },


    newMsg:function(){
        var self = this;

        $.colorbox({
            inline:true,
            scrolling:false,
            overlayClose:false,
            escKey:false,
            title:'Creat New Message',
            href:"#mesg-window"
        });
    },

    saveMessage:function(){
        var self = this;
        /* Validate the form*/
        var validationStatus =  $('#form-new-msg').validationEngine({returnIsValid:true});
        /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
        if(validationStatus){

            var query = 'action=add&'+$('#form-new-msg').serialize();
            var url = $("#messages-url").val();
            /* Send the data to the server and handle the server response */
            $.post(url, query, function(response){
                var txt = '';
                if(typeof response.mesg  == 'object'){
                    for(megTxt in response.mesg){
                        txt += response.mesg[megTxt]+'<br />';
                    }
                }
                else{
                    txt = response.mesg
                }

                if(response.code === 0){
                    /* Alert the user that the server response*/
                    jLib.message(txt, 'success',function(modal){
                        modal.closeModal();
                        window.location = url;
                    });

                    document.getElementById('form-new-msg').reset();
                    $.validationEngine.closePrompt('.formError',true)
                    $.colorbox.close();
                }
                /* When there are Errors */
                else if(response.code === 1){
                    /* Alert the user that the server response*/
                    jLib.setFeedback(txt, 'error_message', false);
                }
            },'json');
        }
    },


    deleteUser:function(grid){
        var url = $('#delete-url').val();
        jLib.do_delete(url,grid);
    }

};

/* when the page is loaded */
$(document).ready(function() {
    Messages.init();
});